//
//  AuthorisationController.m
//  VKChat
//
//  Created by Максим Бризинский on 31.01.11.
//  Copyright 2011 БГУИР. All rights reserved.
//

#import "AuthorisationController.h"

@implementation AuthorisationController

-(void)vkAuthDidSuccess:(VKSessionInfo)session {
	NSLog(@"Authorisation succsess");
	_vkApi.session = session;
	
	NSLog(@"Session: %lld %lld %@ %@",session.mid, session.expire, session.secret, session.sid);
	NSLog(@"Session: %lld %lld %@ %@",_vkApi.session.mid, _vkApi.session.expire, _vkApi.session.secret, _vkApi.session.sid);
	
	[_webView setHidden:YES];
	[_webView removeFromSuperview];

	[_rosterController initRoster];
	
	[_vkApi getPollServerSession];
	[_vkApi startPollServer];
	
	//[self asyncGetYourNameAndStatus];
	[NSThread detachNewThreadSelector:@selector(asyncGetYourNameAndStatus) toTarget:self withObject:nil];
}
-(void)vkAuthDidFail {
	NSLog(@"Authorisation fail");
}



-(void)awakeFromNib {
	_vkApi = [VKApi getInstance];
	
	_vkAuth = [[VKAuth alloc] initWithWebView:_webView];
	_vkAuth.delegate = self;
	
	[NSThread detachNewThreadSelector:@selector(asyncGetSession) toTarget:self withObject:nil];
}

-(void)asyncGetYourNameAndStatus {
	sleep(1);
	NSString* uidString = [NSString stringWithFormat:@"%lld",_vkApi.session.mid];
	NSArray* uidArray = [NSArray arrayWithObject:uidString];
	NSArray* result = [_vkApi getProfilesForUids:uidArray];
	User* user = [result objectAtIndex:0];
	
	if (user != nil) {
		[_yourNameField setStringValue:[NSString stringWithFormat:@"%@ %@",user.firstName, user.lastName]];
	} else {
		NSLog(@"AuthController: can't get name");
	}
	
	sleep(1);
	NSString* status = [_vkApi getStatusForUid:_vkApi.session.mid];
	if (status != nil) {
		[_yourStatusField setStringValue:status];
	} else {
		NSLog(@"Auth controller: can't get status");
	}
}

-(void)asyncGetSession {
	[_vkAuth getSession];
}
@end
